<?php

namespace Simanx\Spes\Module;

use SplFileInfo;
use Symfony\Component\Finder\Finder;

class ModuleManager
{
    /**
     * @var Module[] 模块
     */
    private array $modules = [];

    public function modules(): array
    {
        if ($this->modules) {
            return $this->modules;
        }

        if (!is_dir(config('spes.module.root'))) {
            return $this->modules = [];
        }

        $moduleDirs = iterator_to_array(Finder::create()
            ->directories()
            ->depth(0)
            ->in(config('spes.module.root')));

        /** @var SplFileInfo $moduleDir */
        foreach ($moduleDirs as $moduleDir) {
            $moduleName = $moduleDir->getBasename();
            $this->modules[$moduleName] = new Module($moduleName);
        }

        return $this->modules;
    }

    public function module(string $name)
    {
        return $this->modules()[$name];
    }

    public function hasModule(string $moduleName): bool
    {
        return isset($this->modules()[$moduleName]);
    }

    public function modulesDir(string|null $path = null): array
    {
        $paths = [];
        foreach ($this->modules() as $module) {
            if (($pathInModule = $module->path($path)) != null) {
                $paths[] = $pathInModule;
            }
        }

        return $paths;
    }
}